package com.weishu.auth.controller;

import cn.hutool.crypto.digest.MD5;
import com.weishu.auth.config.AjaxResult;
import com.weishu.auth.form.LoginBody;
import com.weishu.auth.form.Register;
import com.weishu.system.api.domain.SysUser;
import com.weishu.auth.service.ISysUserService;
import com.weishu.auth.service.SysLoginService;
import com.weishu.common.core.domain.R;
import com.weishu.common.core.utils.StringUtils;
import com.weishu.common.security.service.TokenService;
import com.weishu.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * token 控制
 *
 * @author weishu
 */
@RestController
public class TokenController
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form)
    {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @RequestMapping("yzm")
    public String getVerificationCode(){
        String code = "";
        for (int i = 0; i < 4; i++) {
            code += (Math.random()*10)+"";
        }

        redisTemplate.opsForValue().set("verificationCode",code,5,TimeUnit.MINUTES);
        return code;
    }

    @RequestMapping("register")
    public AjaxResult register(@RequestBody Register register){
        String str = (String) redisTemplate.opsForValue().get("phoneyzm");
        if (!register.getYzm().equals(str)){
            System.err.println("error");
            return AjaxResult.err(500,"验证码输入错误");
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserName(register.getUsername());
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(register.getPassword());
        sysUser.setPassword(encode);
        sysUser.setPhonenumber(register.getMobile());
        System.err.println(sysUser);
        boolean b = false;
        try {
            b = iSysUserService.saveOne(sysUser);
        }catch (Exception e){
            return AjaxResult.err(500,"手机号已存在");
        }
        if (b){
            redisTemplate.opsForValue().set("register",sysUser,20, TimeUnit.MINUTES);
            SysUser sysUser1 = iSysUserService.tologin(register.getMobile(), encode);
            LoginUser user = new LoginUser();
            user.setUsername(sysUser1.getUserName());
            user.setSysUser(sysUser1);
            user.setUserid(sysUser1.getUserId());
            Map<String, Object> token = tokenService.createToken(user);
            return AjaxResult.ok(token);
        }
        return AjaxResult.err(500,"注册失败");
    }

    @RequestMapping("registerfirm")
    public AjaxResult registerfirm(@RequestBody SysUser sysUser){
        SysUser user = (SysUser) redisTemplate.opsForValue().get("register");
        sysUser.setUserId(user.getUserId());
        boolean b = iSysUserService.saveOrUpdate(sysUser);
        return AjaxResult.ok(b);
    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            String username = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }
}
